//
//  DR_CollectVC.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/10.
//

import UIKit
import SnapKit

class DR_CollectVC: DR_BaseVC {

    private let recommendedCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 16
        layout.minimumInteritemSpacing = 12
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: 15, right: 15)
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .white
        cv.showsVerticalScrollIndicator = false
        cv.register(DR_RecommendedFileCell.self, forCellWithReuseIdentifier: DR_RecommendedFileCell.identifier)
        return cv
    }()
    
    private var recommendedFiles: [DR_FileModel] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupConstraints()
        loadRecommendedFiles()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 每次显示时刷新文件列表
        loadRecommendedFiles()
    }
    
    private func setupUI(){
        view.addSubview(titleLabel)
        view.addSubview(recommendedCollectionView)
        
        // 设置 collection view
        recommendedCollectionView.delegate = self
        recommendedCollectionView.dataSource = self
    }
    
    private func setupConstraints(){
        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(15)
            make.top.equalTo(view.safeAreaLayoutGuide).offset(24)
            make.height.equalTo(28)
        }
        
        recommendedCollectionView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(16)
            make.leading.trailing.bottom.equalToSuperview()
        }
    }
    
    // MARK: - 加载推荐文件
    private func loadRecommendedFiles() {
        // 获取所有文件作为推荐文件（可以根据实际需求修改筛选逻辑）
        recommendedFiles = DR_FileManager.shared.getAllFiles()
        recommendedCollectionView.reloadData()
    }
    
    private let titleLabel: UILabel = {
        let v = UILabel()
        v.text = "recommend_title".localized
        v.textColor = .black
        v.font = UIFont.systemFont(ofSize: 24, weight: .bold)
        return v
    }()

}

// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension DR_CollectVC: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return recommendedFiles.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DR_RecommendedFileCell.identifier, for: indexPath) as! DR_RecommendedFileCell
        let fileModel = recommendedFiles[indexPath.item]
        cell.configure(with: fileModel)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // 3列布局，计算每个cell的宽度
        let spacing: CGFloat = 12 // 列间距
        let insets: CGFloat = 15 * 2 // 左右边距
        let totalSpacing = spacing * 2 + insets
        let width = (collectionView.bounds.width - totalSpacing) / 3
        return CGSize(width: width, height: 190)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        
        let fileModel = recommendedFiles[indexPath.item]
        
        // PDF 文件使用 DR_LookPDFVC 预览
        if fileModel.fileType == .pdf {
            // 检查PDF是否被锁定
            if DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) {
                // PDF已锁定，需要先输入密码
                showPasswordInputForPDF(fileModel)
            } else {
                // PDF未锁定，直接进入预览
                openPDFPreview(fileModel)
            }
        } else {
            // Word、Excel、PPT 文件使用 DR_LookFileVC 预览
            let previewVC = DR_LookFileVC()
            previewVC.configure(with: fileModel)
            pushHidingTabBar(previewVC, animated: true)
        }
    }
    
    // MARK: - 显示PDF密码输入弹窗
    private func showPasswordInputForPDF(_ fileModel: DR_FileModel) {
        let passwordSheet = DR_EnterPasswordSheet()
        
        // 配置文件信息
        passwordSheet.configure(fileName: fileModel.fileName, fileSize: fileModel.fileSizeString)
        
        passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
            guard let self = self, let sheet = passwordSheet else { return }
            
            // 验证密码
            if DR_PDFTool.shared.verifyPassword(for: fileModel.fileURL, password: password) {
                // 密码正确，关闭弹窗并进入预览
                sheet.hide()
                // 等待弹窗隐藏动画完成后再push
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    self.openPDFPreview(fileModel, isPasswordVerified: true)
                }
            } else {
                // 密码错误，显示错误信息（不关闭弹窗）
                sheet.showError()
            }
        }
        
        passwordSheet.onCancel = {
            // 取消操作，不需要处理
        }
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            passwordSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            passwordSheet.show(in: tabBarController.view)
        } else {
            passwordSheet.show(in: view)
        }
    }
    
    // MARK: - 打开PDF预览
    private func openPDFPreview(_ fileModel: DR_FileModel, isPasswordVerified: Bool = false) {
        let pdfModel = DR_PDFFileModel(
            fileName: fileModel.fileName,
            fileURL: fileModel.fileURL,
            fileSize: fileModel.fileSize,
            createDate: fileModel.createDate,
            pageCount: fileModel.pageCount
        )
        
        let previewVC = DR_LookPDFVC()
        previewVC.configure(with: pdfModel, isPasswordVerified: isPasswordVerified)
        pushHidingTabBar(previewVC, animated: true)
    }
}
